package com.biscuit.page.basicservice.service;

import com.biscuit.page.basicservice.api.model.request.ai_chat.AiChatAbortDialogueAReq;
import com.biscuit.page.basicservice.api.model.request.ai_chat.AiChatBuildDialogueResultAReq;
import com.biscuit.page.basicservice.api.model.request.ai_chat.AiChatInitiateChatDialogueAReq;
import com.biscuit.page.basicservice.api.model.response.ai_chat.AiChatBuildDialogueResultAResp;
import com.biscuit.page.basicservice.conf.handler.UserContextHandler;
import com.biscuit.page.basicservice.model.entities.mysql.SysAiChatDialogue;
import com.biscuit.page.basicservice.model.entities.mysql.SysAiChatSession;
import com.biscuit.page.basicservice.persistence.dao.AiChatDialogueDao;
import com.biscuit.page.basicservice.persistence.dao.AiChatDialogueRebuildDao;
import com.biscuit.page.basicservice.persistence.dao.AiChatSessionDao;
import com.biscuit.page.basicservice.utils.BaseExceptionUtil;
import com.biscuit.page.basicservice.utils.BaseThreadUtil;
import com.biscuit.page.basicservice.utils.BaseVerifyUtil;
import com.biscuit.page.basicservice.utils.VolcanoUtil;
import com.biscuit.page.basicservice.websocket.ai_chat.AiChatSessionWebSocketContext;
import com.biscuit.page.basicservice.websocket.ai_chat.AiChatSessionWebSocketHandler;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author biscuit
 * @create 2024年07月31日 17:47
 */
@Slf4j
@Service
public class AiChatService {

    @Resource
    private VolcanoService volcanoService;

    @Resource
    private AiChatSessionDao aiChatSessionDao;

    @Resource
    private AiChatDialogueDao aiChatDialogueDao;

    @Resource
    private AiChatDialogueRebuildDao aiChatDialogueRebuildDao;


    public String execNewChatSession() {
        // 新增AI聊天会话
        SysAiChatSession aiChatSession = new SysAiChatSession();
        aiChatSession.setUserId(UserContextHandler.getUserIdOr0());
        this.aiChatSessionDao.insertAndIncrement(aiChatSession);

        // 返回会话自增ID
        return aiChatSession.getId().toString();
    }

    public String execInitiateChatDialogue(AiChatInitiateChatDialogueAReq req) {
        // 参数校验
        BaseExceptionUtil.throwException(
                StringUtils.isNotBlank(req.getQuestion()) && StringUtils.isNotBlank(req.getQuestion().replace(" ", "")),
                "问题不能为空"
        );
        BaseExceptionUtil.throwException(BaseVerifyUtil.verifyNumberFullValid(req.getSessionId()), "会话ID为空");

        // 根据 会话ID 查询会话
        SysAiChatSession aiChatSession = this.aiChatSessionDao.getById(req.getSessionId());

        // 判断会话是否存在
        BaseExceptionUtil.throwException(Objects.nonNull(aiChatSession), "会话不存在");

        // 新增 AI 聊天对话
        SysAiChatDialogue aiChatDialogue = new SysAiChatDialogue();
        aiChatDialogue.setQuestion(req.getQuestion());
        aiChatDialogue.setSessionId(aiChatSession.getId());
        this.aiChatDialogueDao.insertAndIncrement(aiChatDialogue);

        // 返回 对话自增ID
        return aiChatDialogue.getId().toString();
    }

    public void execBuildDialogueResult(AiChatBuildDialogueResultAReq req) {
        // 参数校验
        BaseExceptionUtil.throwException(StringUtils.isNotBlank(req.getQuestion()), "问题不能未空");
        BaseExceptionUtil.throwException(BaseVerifyUtil.verifyNumberFullValid(req.getSessionId()), "非法会话ID");
        BaseExceptionUtil.throwException(BaseVerifyUtil.verifyNumberFullValid(req.getDialogueId()), "非法对话ID");

        // 查询对话信息
        SysAiChatDialogue aiChatDialogue = this.aiChatDialogueDao.getById(req.getDialogueId());

        // 判断对话是否存在
        BaseExceptionUtil.throwException(Objects.nonNull(aiChatDialogue), "对话不存在");

        // 获取会话 Context 对象
        AiChatSessionWebSocketContext context = AiChatSessionWebSocketHandler.getContext(req.getSessionId());

        // 校验会话是否建立连接
        BaseExceptionUtil.throwException(Objects.nonNull(context), "会话未建立连接");

        // 查询当前对话所在会话内，近 5 分钟内的对话信息
        List<SysAiChatDialogue> aiChatDialoguesList =
                this.aiChatDialogueDao.listBySessionIdAndMinuteBefore(aiChatDialogue.getSessionId(), 5);


        // 开始异步生成对话结果，基于 WebSocket 进行回显
        List<ChatMessage> chatMessageList = VolcanoUtil.buildChatMessageByAiChatDialogue(aiChatDialoguesList, req.getQuestion());
        this.volcanoService.asyncAiChat(
                chatMessageList, context
                );
    }

    public void execRebuildDialogueResult(Long dialogueId) {
    }

    public void execAbortDialogue(AiChatAbortDialogueAReq req) {
    }

}
